<template>
  <!-- 学习成果组件 根据时间 -->
  <div class="studyResultBox" v-loading="loading">
    <div class="operation flexBet" v-if="type == 'edit'">
      <div class="flex">
        <!-- <img class="shou menu" src="@/assets/images/studyResults/menu.png" alt="加载失败" @click="intoAdd"
          v-if="mode == 'normal'" /> -->
      </div>

      <div class="flex btns">
        <el-button
          v-if="mode == 'normal'"
          v-preventReClick
          size="mini"
          type="primary"
          @click.stop="intoAdd"
          >添加优秀成果
        </el-button>
        <el-button
          v-if="mode == 'add'"
          style="width: 80px"
          v-preventReClick
          size="mini"
          type="primary"
          @click.stop="mode = 'normal'"
          >取 消
        </el-button>
        <el-button
          v-if="selectedResults.length > 0 && mode == 'add'"
          style="width: 80px"
          v-preventReClick
          size="mini"
          type="primary"
          @click.stop="handleView"
          >预 览
        </el-button>
        <el-button
          style="width: 80px"
          v-if="mode == 'add'"
          v-preventReClick
          size="mini"
          type="primary"
          @click.stop="handleAdd"
          >确 认({{ selectedResults.length }})
        </el-button>
      </div>
    </div>

    <!-- ！！！展示组件 -->
    <div
      class="showBox infinite-list"
      v-infinite-scroll="load"
      :style="{ height: height }"
      v-if="showResults.length > 0"
    >
      <!-- 根据日期循环-->
      <div
        class="showBox_item"
        v-for="(dateItem, dateIndex) in showResults"
        :key="dateIndex"
      >
        <div class="time">{{ dateItem.date }}</div>
        <div class="cards">
          <!-- 根据时间循环 -->
          <div
            class="card_item"
            v-for="(timeItem, timeIndex) in dateItem.times"
            :key="timeIndex"
          >
            <div
              class="flex card_item_time"
              v-if="timeItem.fileInfo.length > 0"
            >
              <img
                class="card_item_img"
                src="@/assets/images/studyResults/time.png"
                alt="加载失败"
              />
              <div class="label">
                {{
                  formatter == "byDate" ? timeItem.time : timeItem.time + "时"
                }}
              </div>
            </div>
            <div
              class="card_item_content_border"
              v-if="timeItem.fileInfo.length > 0"
            >
              <div
                class="card_item_content flex"
                :style="{
                  width: (size == 'normal' ? 160 : 110) * num + 10 + 'px',
                }"
              >
                <!-- 文件 -->
                <div
                  :class="[
                    size == 'normal'
                      ? 'card_item_content_file'
                      : 'card_item_content_filemini',
                    'rela',
                    'shou',
                    'flexcen',
                    'flexcolcenter',
                  ]"
                  @click="fileClick(timeItem.fileInfo, fileItem, fileIndex)"
                  v-for="(fileItem, fileIndex) in timeItem.fileInfo"
                  :key="fileIndex"
                >
                  <div @click.stop="" class="file_item_checkbox shou absolute">
                    <el-checkbox
                      v-if="mode == 'add'"
                      @change="checkboxClick($event, fileItem)"
                      v-model="fileItem.selected"
                      :disabled="fileItem.disable"
                    >
                    </el-checkbox>
                  </div>
                  <img
                    class="file_img"
                    v-if="isImage(fileItem.url)"
                    :src="fileItem.url"
                    alt="加载失败"
                  />
                  <video
                    class="file_video"
                    v-else-if="isVideo(fileItem.url)"
                    :src="fileItem.url"
                  ></video>
                  <div class="file" v-else>
                    <img
                      :src="returnIcon(fileItem.url, 1)"
                      alt="加载失败"
                      class="icon"
                    />
                    <tooltip
                      :width="size == 'normal' ? '140' : '90'"
                      class="filename"
                      :text="fileItem.name"
                    ></tooltip>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!--  -->
    </div>
    <div v-else :style="{ height: height }">
      <el-empty description="暂无学习成果"></el-empty>
    </div>

    <!-- 关闭 -->
    <div
      class="flexEnd btns"
      style="margin-top: 20px; width: 100%"
      v-if="type == 'edit'"
    >
      <el-button
        style="width: 80px"
        v-preventReClick
        size="mini"
        type="primary"
        @click="close"
        >关 闭
      </el-button>
    </div>
    <!-- 预览 -->
    <fileDrawer
      :preview="preview"
      :show.sync="drawer"
      :url="drawerurl"
      :name="drawername"
      :paramsIndex="drawerIndex"
      :type="1"
    ></fileDrawer>
  </div>
</template>

<script>
import { returnIcon, isVideo, isImage } from "@/utils/util.js";
import {
  learningResult,
  learningResultMine,
  addExcellentLearningResult,
} from "@/api/studyResult/studyResult";
import tooltip from "./tooltip.vue";

export default {
  components: { tooltip },
  props: {
    num: {
      type: [String, Number],
      default: 5,
    },
    size: {
      type: String,
      default: "normal",
    },
    className: {
      type: String,
      default: "",
    },
    // 用于获取学习成果的id
    courseId: [Number, String],
    // 类型 :edit view
    type: {
      type: String,
      default: "view",
    },
    height: {
      type: String,
      default: "calc(94vh - 60px - 200px)",
    },
    formatter: {
      type: String,
      default: "byDate",
    },
  },
  data() {
    return {
      preview: null,
      drawer: false,
      drawerurl: "",
      drawerIndex: "",
      drawername: "",
      returnIcon: function (url, type) {
        return returnIcon(url, type);
      },
      isVideo: function (url) {
        return isVideo(url);
      },
      isImage: function (url) {
        return isImage(url);
      },
      loading: false,
      // normal add
      mode: "normal",
      // 存放原学习成果
      results: [],
      // 用于显示的学习成果
      showResults: [],
      // 选中的数组
      selectedResults: [],
      // 用于预览的数组
      previewResults: [],
      indexId: "",
    };
  },
  mounted() {},
  methods: {
    fileClick(files, fileitem, index) {
      console.log(files, fileitem);
      if (this.mode == "add" && !fileitem.disable) {
        fileitem.selected = !fileitem.selected;
        this.$forceUpdate();
        if (fileitem.selected) {
          this.selectedResults.push(fileitem);
        } else {
          this.selectedResults = this.selectedResults.filter((item) => {
            return item.url != fileitem.url;
          });
        }
      } else {
        console.log("预览", files);
        this.drawer = true;
        this.drawerurl = files;
        this.drawerIndex = index;
      }
    },
    formatterTime(isoTime) {
      let date = new Date(isoTime);

      // 格式化日期和时间
      let year = date.getFullYear();
      let month = ("0" + (date.getMonth() + 1)).slice(-2); // getMonth()返回0-11，所以需要+1
      let day = ("0" + date.getDate()).slice(-2);
      let hours = ("0" + date.getHours()).slice(-2);
      let minutes = ("0" + date.getMinutes()).slice(-2);
      let seconds = ("0" + date.getSeconds()).slice(-2);

      let formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      return formattedTime;
    },
    // 自行的result处理 合并所有里面的times
    // result.map((item) => {
    //   let fileInfo = [];
    //   item.times.map((time) => {
    //     time.fileInfo.map((file) => {
    //       file.ancestorsName = time.ancestorsName;
    //       file.answerId = time.answerId;
    //       file.createTime = time.createTime;
    //       file.indexId = time.indexId;
    //       file.lrId = time.lrId;
    //       file.selected = time.selected;
    //       file.studentId = time.studentId;
    //     });
    //     fileInfo = [...fileInfo, ...time.fileInfo];
    //   });
    //   item.times = [{ fileInfo: fileInfo, time: item.hour }];
    // });
    organizeImagesByDate(answers) {
      const groupedData = {};

      answers.forEach((answer) => {
        const date = answer.createTime.split(" ")[0];
        const timeOnly = answer.createTime.split(" ")[1]; // 提取时间部分
        let answerObj = { ...answer };
        answer.fileInfo.map((file) => {
          file = { ...file, ...answerObj };
        });
        if (!groupedData[date]) {
          groupedData[date] = { times: [], date: date };
        }

        // 在复制的对象中新增time字段，以避免修改原始数据
        const enhancedAnswer = { ...answer, time: timeOnly, selected: false };
        groupedData[date].times.push(enhancedAnswer);
      });

      // 直接转换为最终结构，无需额外映射操作，因为我们已经按需构建了对象
      return Object.values(groupedData);
    },
    // 用于总结小时
    mergeFileInfosByHour(dataArray) {
      const mergedDataArray = [];

      dataArray.forEach((day) => {
        const hourlyFileInfoMap = {};

        day.times.forEach((timeEntry) => {
          const hour = timeEntry.time.split(":")[0];
          if (!hourlyFileInfoMap[hour]) {
            hourlyFileInfoMap[hour] = [];
          }
          hourlyFileInfoMap[hour] = hourlyFileInfoMap[hour].concat(
            timeEntry.fileInfo
          );
        });

        // 将小时按倒序排列
        const sortedHours = Object.keys(hourlyFileInfoMap).sort((a, b) =>
          b.localeCompare(a)
        );

        // 构造新的times结构，根据倒序的小时
        const mergedTimes = sortedHours.map((hour) => ({
          time: hour,
          fileInfo: hourlyFileInfoMap[hour],
        }));

        mergedDataArray.push({
          date: day.date,
          times: mergedTimes,
        });
      });

      return mergedDataArray;
    },
    //获取所有的学习成果(该组件一般采取 外面获取的方式)
    // query用于学生个人中心 item=='mine'
    // preview 用于成果预览的 章节 学生名称显示
    async getALLresult(item, query, preview) {
      this.mode = "normal";
      this.preview = preview ? preview : null;
      console.log(
        "获取所有的学习成果(该组件一般采取 外面获取的方式)",
        item,
        query,
        preview
      );
      // item=='mine'从我的中心进入的
      if (item.type == "mine") {
        console.log("query", query);
        this.loading = true;
        this.showResults = [];
        let res = await learningResultMine({
          ...query,
          ...{ studentId: item.studentId },
        });
        let paramsItem = item;
        try {
          if (res.code == 200) {
            this.previewResults = [];
            res.data.map((item) => {
              item.fileInfo = JSON.parse(item.fileInfo);
              // 处理成可预览的数组
              item.createTime = this.formatterTime(item.createTime);
              item.fileInfo.map((file) => {
                file.ancestorsName = item.ancestorsName;
                file.createTime = item.createTime;
                file.studentName = paramsItem.studentName
                  ? paramsItem.studentName
                  : this.$store.getters.name;
                file.className = this.className
                  ? this.className
                  : paramsItem.className
                  ? paramsItem.className
                  : null;
                file.studentId = paramsItem.studentName
                  ? paramsItem.studentId
                  : this.$store.getters.studentId;
                file.studentNum = paramsItem.studentName
                  ? paramsItem.studentNum
                  : this.$store.getters.account;
                console.log(
                  this.$store.getters,
                  file,
                  paramsItem,
                  paramsItem.studentName,
                  paramsItem.studentNum
                );
              });
              this.previewResults = [...this.previewResults, ...item.fileInfo];
            });
            this.previewResults.map((item, index) => {
              item.fileIndex = index;
            });
            this.results = res.data;

            // 处理成展示的数组
            if (this.formatter == "byDate") {
              // 处理成展示的数组
              this.showResults = this.organizeImagesByDate(this.results);
            } else {
              // 处理成展示的数组
              this.showResults = this.mergeFileInfosByHour(
                this.organizeImagesByDate(this.results)
              );
            }
            console.log("处理成展示的数组", this.showResults);
          }
        } finally {
          this.loading = false;
        }
      }
      // 正常进入
      else {
        console.log("item.type", item.type);
        if (item.type == "teacherIndex") {
          this.indexId = item.item.id;
        } else {
          this.indexId = item.indexId;
        }
        this.loading = true;
        // 重置选中
        this.mode = "normal";
        this.selectedResults = [];
        let data = { ...query };
        let res = await learningResult(this.indexId, {
          studentId: this.$route.query.studentId
            ? this.$route.query.studentId
            : this.$store.getters.roleId == "student"
            ? this.$store.getters.studentId
            : "",
          courseId: data.courseId,
          classId: data.classId,
          courseSchedulingId: data.courseSchedulingId,
        });
        this.previewResults = [];
        const arr = [];
        res.data.map((item, index) => {
          if (item.fileInfo && item.fileInfo.length > 1) {
            item.fileInfo = JSON.parse(item.fileInfo);
            item.fileInfo.map((file) => {
              file.ancestorsName = item.ancestorsName;
              file.createTime = item.createTime;
              file.studentName = item.studentName;
              file.studentNum = item.studentNum;
              file.className = this.className;
              let lrId = item.lrId ? item.lrId.split(",") : [];
              if (lrId.includes(file.url)) {
                file.disable = true;
              }
            });
            // 处理成可预览的数组
            this.previewResults = [...this.previewResults, ...item.fileInfo];
            arr.push(item);
          }
        });
        this.results = arr;
        if (this.formatter == "byDate") {
          // 处理成展示的数组
          this.showResults = this.organizeImagesByDate(this.results);
        } else {
          // 处理成展示的数组
          this.showResults = this.mergeFileInfosByHour(
            this.organizeImagesByDate(this.results)
          );
        }

        console.log(this.showResults);
        this.loading = false;
      }
    },

    load() {
      console.log("加载下一页");
    },
    // 进入编辑模式
    intoAdd() {
      this.mode = "add";
      // 置空所有的selected
      this.selectedResults = [];
    },
    // 选中事件
    checkboxClick(e, i) {
      if (e) {
        this.selectedResults.push(i);
      } else {
        this.selectedResults = this.selectedResults.filter((item) => {
          return item.url != i.url;
        });
      }
      console.log(this.selectedResults);
    },
    async handleAdd() {
      if (this.selectedResults.length == 0) {
        this.$message.warning("请选择要添加的学习成果");
        return;
      }
      let arr = JSON.parse(JSON.stringify(this.results));
      arr.forEach((item) => {
        item.file = item.fileInfo
          .filter((subItem) => subItem.selected)
          .map((subItem) => {
            return { name: subItem.name, url: subItem.url };
          });
        delete item.createTime;
        delete item.fileInfo;
        delete item.lrId;
      });
      let data = {
        courseId: this.courseId,
        indexId: this.indexId,
        learningResultInfoParams: arr,
      };
      let res = await addExcellentLearningResult(data);
      // 添加成功
      if (res.code == 200) {
        this.mode = "normal";
        this.$message({
          type: "success",
          message: "添加成功",
        });
        this.getALLresult({
          indexId: this.indexId,
        });
      }
    },
    handleView() {
      const selected = this.previewResults.filter((item) => {
        return item.selected == true;
      });
      this.drawer = true;
      this.drawerurl = selected;
      this.drawerIndex = 0;
    },
    close() {
      if (this.selectedResults.length > 0) {
        this.$confirm("是否放弃添加优秀学习成果?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.$emit("close");
          })
          .catch(() => {});
      } else {
        this.$emit("close");
      }
    },
  },
};
</script>
<style scoped lang="scss">
.btns {
  ::v-deep .el-button--mini {
    height: 40px;
    border-radius: 12px;
    font-size: 16px;
    font-weight: 400;
  }
}

.studyResultBox {
  .operation {
    height: 40px;

    .title {
      margin-top: 5px;
      font-size: 18px;
      font-weight: 400;
      color: rgba(0, 0, 0, 1);
    }

    .menu {
      width: 14px;
      height: 13px;
      margin: 11px 0 0 5px;
    }
  }

  .showBox {
    box-sizing: border-box;
    margin-top: 10px;
    overflow-y: auto;
    margin-left: 6px;
    padding-right: 10px;

    .showBox_item {
      margin-bottom: 10px;

      .time {
        font-size: 12px;
        font-weight: 400;
        color: rgba(166, 166, 166, 1);
      }

      .cards {
        .card_item {
          margin-top: 10px;

          .card_item_time {
            .label {
              margin: 0 0 0 22px;
              font-size: 12px;
              font-weight: 400;
              color: rgba(51, 51, 51, 0.8);
            }

            img {
              margin-left: 8px;
              width: 12px;
              height: 14px;
            }
          }

          .card_item_content_border {
            margin-top: 5px;
            margin-left: 14px;
            padding-left: 27px;
            border-left: 1px solid rgba(229, 229, 229, 1);

            .card_item_content {
              background: #e6e6e6;
              box-sizing: border-box;
              padding: 0 10px 10px 0;
              border-radius: 8px;

              .card_item_content_filemini {
                margin: 10px 0 0 10px;
                width: 100px;
                height: 73px;
                background: white;
                box-sizing: border-box;

                .file {
                  width: 100%;
                  height: 100%;

                  .icon {
                    margin: 7px 0 0 32px;
                    width: 40px;
                    height: auto;
                  }

                  .filename {
                    text-align: center;
                    font-size: 12px;
                    margin: 0 0 0 10px;
                  }
                }

                .file_item_checkbox {
                  top: 5px;
                  right: 9px;
                }

                .file_img {
                  max-width: 100%;
                  max-height: 100%;
                  object-fit: contain;
                  /* 保持图片原始宽高比，并缩放至最大能适应容器的大小 */
                  margin: auto;
                  /* 图片居中 */
                }

                .file_video {
                  width: 100%;
                  height: 100%;
                }
              }

              .card_item_content_file {
                margin: 10px 0 0 10px;
                width: 150px;
                height: 110px;
                background: white;
                box-sizing: border-box;

                .file {
                  width: 100%;
                  height: 100%;

                  .icon {
                    margin: 20px 0 0 50px;
                    width: 50px;
                    height: auto;
                  }

                  .filename {
                    text-align: center;
                    margin: 10px 0 0 10px;
                  }
                }

                .file_item_checkbox {
                  top: 5px;
                  right: 9px;
                }

                .file_img {
                  max-width: 100%;
                  max-height: 100%;
                  object-fit: contain;
                  /* 保持图片原始宽高比，并缩放至最大能适应容器的大小 */
                  margin: auto;
                  /* 图片居中 */
                }

                .file_video {
                  width: 100%;
                  height: 100%;
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>
